package simple.word;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;

public class RawParse {
	
	static Options makeOptions() {
		Options options = new Options();
		
		options.addOption(new Option("i", true, "Input file"));
		
		return options;
	}
	
	static void usage(Options options) {
		HelpFormatter formatter = new HelpFormatter();
		
		formatter.printHelp("java -cp <classpath> " + RawParse.class.getName(), options);
	}
	
	public static void main(String [] args) throws Exception {
		String fileName = null;
		
		Options options = makeOptions();
		
		try {
			PosixParser parser = new PosixParser();
			CommandLine line = parser.parse(options, args);
			
			if(line.hasOption("i"))
				fileName = line.getOptionValue("i");
			
			if(fileName == null) {
				System.out.println("Missing input file");
				usage(options);
				System.exit(1);				
			}
		} catch (ParseException ex) {
			usage(options);
			System.exit(1);
		}
		
		File file = new File(fileName);
		if(!file.exists()) {
			System.out.println("File doesn't exit : " + file.getAbsolutePath());
			System.exit(1);			
		}
		
		try(
				FileInputStream fis = new FileInputStream(file);
				InputStreamReader isr = new InputStreamReader(fis, "utf-8");
				BufferedReader br = new BufferedReader(isr);
				) {
			String line;
			while((line = br.readLine()) != null) {
				line = line.trim();
				if(line.equals("Add a note"))
					continue;
				
				int pos = line.indexOf("Read more at location");
				if(pos == -1)
					continue;
				String sub = line.substring(0, pos);
				int counter = 0;
				int length = sub.length();
				
				for(; counter < length; ++ counter) {
					char x = sub.charAt(length - counter - 1);
					if(Character.isAlphabetic(x))
						break;
				}
				sub = sub.substring(0, length - counter);
				System.out.println(sub);
			}
		}
	}
}
